<?php
use Workerman\Worker;
use Workerman\Lib\Timer;
require_once __DIR__ . '/Autoloader.php';
require_once __DIR__.'/mysql/src/Connection.php';
require_once __DIR__ . '/channel/Server.php';
require_once __DIR__ . '/channel/Client.php';

define('HEARTBEAT_TIME', 10);


// $channel_server = new Channel\Server('0.0.0.0', 2206);
// 创建一个Worker监听2345端口，使用http协议通讯
$http_worker = new Worker("websocket://127.0.0.1:8000");

$http_worker->count = 3;

$http_worker->name = 'ceshi';
// 设置所有连接的默认应用层发送缓冲区大小
// TcpConnection::$defaultMaxSendBufferSize = 2*1024*1024;
// 设置每个连接接收的数据包最大为1024000字节
// TcpConnection::$maxPackageSize = 1024000;
// $memberid ='';
$http_worker->onError = function($connection, $code, $msg)
{
    echo "error $code $msg\n";
};
//进程数量
$http_worker->onWorkerStart = function($http_worker){

    //Channel\Client::connect('0.0.0.0', 2206);

    // Channel\Client::on('broadcast',function($event_data)use($http_worker){
    //     foreach($http_worker->connections as $connection)
    //         {
    //             $connection->send($event_data);
    //         }
    // });
    
    //if($http_worker->id ==0){
        // \Workerman\Lib\Timer::add(2, function () use ($http_worker) {
        //     // global $s;
        //     // $s++;
        //     foreach($http_worker->connections as $connection)
        // {
        //     $connection->send(time());
        // }
        //     // echo $s;
            
        // });
    //}
    //进程id
    // if($http_worker->id ==1){
    //     echo 's';
    // }
    
    // global $db;
    // $db = new \Workerman\MySQL\Connection('192.168.0.191', '3306', 'root', '123456', 'jmft_cxh');
    
    // \Workerman\Lib\Timer::add(1,function() use ($http_worker){
        
    //     $time_now = time();
    //     foreach($http_worker->connections as $connection)
    //     {
    //         // print_r($connection);
    //         if(empty($connection->lastMessageTime)){
    //             $connection->lastMessageTime = $time_now;
    //             continue;
    //         }
    //         if ($time_now - $connection->lastMessageTime > HEARTBEAT_TIME) {
    //             $connection->send('用户'.$connection->id.'超时关闭连接');
    //             $connection->close();
    //         }
    //     }
    // });

    
};

//  客户信息
$http_worker->onConnect= function($onconnect){ 
    
    // echo $onconnect->getRemotePort();
    // echo '<br>';
    //用户id
    // $memberid = $onconnect->id;
    // echo $onconnect->id;
    // echo '<br>';
    // echo $onconnect->getRemoteIp();
    // print_r($onconnect->worker);
    //缓冲区 
    //$onconnect->maxSendBufferSize=10240;

    $onconnect->lastMessageTime = time();



};
$http_worker->onMessage = function($connection, $data)
{
    
    // print_r($http_worker->connections);
    // 向浏览器发送hello world
    // $arr =array();
    // $arr['1'] = $connection;
    // $arr['2'] = $data;
    // $arr = json_encode($arr);
    // $port = $connection->getRemotePort();
    //发送到所有用户
    // foreach($connection->worker->connections as $con){
    //     $con->send('haha');
    // }
    // $event_data = $data;
    // 绑定事件
    // \Channel\Client::publish('broadcast',$event_data);
    
     // 通过全局变量获得db实例
    // global $db;
    // $sql = 'SELECT realname FROM ims_ewei_shop_member WHERE id =1';
    // $date = $db->query($sql);
    $connection->send("you just send".$data);
   
    
    
};

$http_worker->onClose = function ($connection) {
    // global $group_con_map;
    // if (isset($connection->no)) {
    //     unset($group_con_map[$connection->no]);
    // }
};
// 运行worker
Worker::runAll();










//创建websocket服务器对象，监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("192.168.188.128", 9502);
//设置异步任务的工作进程数量
$ws->set(array('task_worker_num' => 4));

$ws->on('connect', function ($ws, $id) {  
    echo "Client: Connect.\n";

    go(function(){
        echo 222;
    })
});
//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
	//print_r($request);
    $ws->push($request->fd, "hello, welcome\n");
});
// $ws->on('WorkerStart', function ($server, $worker_id) { 
   
//     // if ($worker_id == 1) { 
//     swoole_timer_tick(2000, function ($timer_id) { echo "tick-2000ms\n $worker_id"; });
//     // }
// });
//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
    
    $task_id = $ws->task($frame);
    echo "Dispath AsyncTask: id=$task_id\n";
    //echo "Message: {$frame->data}\n";
    $ws->push($frame->fd, "server: $frame->data");
});


//处理异步任务
$ws->on('task', function ($ws, $task_id, $from_id, $data) {
    echo "New AsyncTask[id=$task_id]".PHP_EOL;
    print_r($from_id);
    //$ws->push($from_id,"server: $data");
    //返回任务执行的结果
    $ws->finish("$data -> OK");
});

//处理异步任务的结果
$ws->on('finish', function ($ws, $task_id, $data) {
    echo "AsyncTask[$task_id] Finish: $data".PHP_EOL;
});

//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
    echo "client-{$fd} is closed\n";
});

$ws->start();
?>